package com.sdry.config;

import com.sdry.system.entity.SysUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description 登陆拦截
 * @Author chenBin
 * @Date 2020-04-09 16:11
 * @Version 1.0
 **/
public class LoginInterceptor implements HandlerInterceptor {
    /**不拦截的**/
    private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();
    private static final String API_URL = "/api";
    private static final String LOGIN_URL = "/toLogin";
    private static final String STATIC_URL = "/static";
    private static final String ERROR_URL = "/error";
    static {
        NOT_INTERCEPT_URI.add("/toLogin");
        NOT_INTERCEPT_URI.add("/api");
        NOT_INTERCEPT_URI.add("/getCode");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //不拦截
        if (NOT_INTERCEPT_URI.contains(uri)) {
            return true;
        }
        if (uri.contains(API_URL) || uri.contains(LOGIN_URL) || uri.contains(STATIC_URL) || uri.contains(ERROR_URL)) {
            return true;
        }
        //拦截
        HttpSession session=request.getSession();
        SysUser userInfo = (SysUser)session.getAttribute("user");
        String requestHeader = request.getHeader("X-Requested-With");
        if(userInfo==null){
            if ("XMLHttpRequest".equalsIgnoreCase(requestHeader)) {
                response.setHeader("sessionStatus","timeout");
            }else {
                response.sendRedirect(request.getContextPath()+"/toLogin");
                return false;
            }
        }
        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
